package bar.dark.lee.fan;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.select.SelectData;

public class FanOutInsertActivity extends SuperActivity
{
	/** 값은 돈 인지 수정인지 입력인지에 대한 플레그 키 값*/
	public static final String INSERT_FLAG = "insert_flag";
	
	/** 입력 */
	public static final int INSERT = 0;
	/** 수정 */
	public static final int UPDATE = 1;
	/** 값은 돈 */
	public static final int CHECK = 2;
	
	public static final int UPDATE_DETAIL = 3;
	
	/** 체크카드  다이얼로그 엑티비티 리퀘스트 키 값 */
	private static final int REQUEST_CHECK = 0;
	/** 전화번호 엑티비티 리퀘스트 키 값 */
	private static final int REQUEST_TEL_NAME = 1;
	/** 카테고리 다이얼로그 엑티비티 리퀘스트 값*/
	private static final int REQUEST_CATEGORY = 2;
	/** 신용카드 다이얼로그 엑티비티 리퀘스트 키 값 */
	private static final int REQUEST_CREDIT = 3;
	/** 통장 다이얼로그 엑티비티 리퀘스트 키 값 */
	private static final int REQUEST_BANK = 4;
	
	/** 없음 단어 값 */
	public final String NONE = "없음";
	
	private DBSQLite sql;
	
	/** 현금 라디오버튼 */
	private RadioButton realRadio; 
	/** 체크카드 라디오버튼 */
	private RadioButton checkRadio;
	/** 통장 라디오버튼 */
	private RadioButton bankRadio;
	/** 신용카드 라디오버튼 */
	private RadioButton creditRadio;
	
	/** 날짜 버튼 뷰 */
	private View dateView;
	/** 날짜 텍스트 뷰  */
	private TextView dateTextView;
	
	/** 카테고리 버튼 뷰 */
	private View categoryView;
	/** 카테고리 텍스트 뷰 */
	private TextView categoryTextView;
	
	/** 체크카드 뷰*/
	private View checkView;
	/** 체크카드 텍스트 뷰*/
	private TextView checkTextView;
	/** 통장 뷰*/
	private View bankView;
	/** 통장 텍스트 뷰*/
	private TextView bankTextView;
	/** 신용카드 뷰*/
	private View creditView;
	/** 신용카드 텍스트 뷰*/
	private TextView creditTextView;
	
	/** 이름 버튼 뷰*/
	private View nameView;
	/** 이름 텍스트 뷰 */
	private TextView nameTextView;
	/** 이름 버튼 직접입력 화살표*/
	private ImageView nameArrow;
	/** 이름 텍스트 직접입력 뷰 */
	private EditText nameEditTextView;
	
	/** 전화번호 버튼 뷰*/
	private View telView;
	/** 전화번호 텍스트 뷰 */
	private TextView telTextView;
	/** 전화번호 직접입력 화살표*/
	private ImageView telArrow;
	/** 전화번호 직접입력 텍스트 뷰 */
	private EditText telEditTextView;
	
	private View outTotalMoneyView;
	private View outMyMoneyView;
	private TextView outTotalMoneyText;
	private TextView outMyMoneyText;
	
	private TextView moneyText;
	/** 빌려준 금액 에디트 텍스트 뷰 */
	private EditText moneyEdit;
	
	/** 메모 뷰 */
	private View memoView;
	/** 메모 에디트 텍스트 뷰 */
	private EditText memoEdit;
	
	private Button deleteButton;
	private Button listButton;
	
	private Button insertButton;
	
	private ArrayList<String> categoryList = new ArrayList<String>();
	private ArrayList<String> checkCardList = new ArrayList<String>();
	private ArrayList<String> bankBookList = new ArrayList<String>();
	private ArrayList<String> creditCardList = new ArrayList<String>();
	
	private int year;
	private int month;
	private int day;
	
	/** 링크에 넣을 아이디 값 */
	private int maxId = -1;
	
	private Intent getIntent;
	
	private int inOutflag;
	
	/** 부채 테이블 데이터 */
	private FanData infoData = null;
	
	/** 해결 유무에 대한 데이터 값 */
	private SelectData checkData = null;
	
	private String message = "";
	
	private int inputType;
	
	private BigDecimal myOutMoney = BigDecimal.ZERO;
	private BigDecimal myInMoney = BigDecimal.ZERO;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(this);
		
		setGoneTipButton();
		
		setContentView(R.layout.fan_out_insert_activity);
		
		getIntent = getIntent();

		inOutflag = getIntent.getIntExtra(INSERT_FLAG, 0);
		
		if (inOutflag == INSERT)
		{
			setTitle("빌려준금액 추가");
		}
		else if (inOutflag == UPDATE)
		{
			setTitle("빌려준금액 수정");
		}
		else if (inOutflag == CHECK)
		{
			setTitle("갚은금액");
		}
		else if (inOutflag == UPDATE_DETAIL)
		{
			setTitle("갚은금액 수정");
		}
		
		setFindView();
		setOnClickListener();
		setData();
	}

	private void setFindView()
	{
		realRadio = (RadioButton) findViewById(R.id.fanOutInsertRealRadio);
		checkRadio = (RadioButton) findViewById(R.id.fanOutInsertCheckRadio);
		bankRadio = (RadioButton) findViewById(R.id.fanOutInsertBankRadio);
		creditRadio = (RadioButton) findViewById(R.id.fanOutInsertCreditRadio);
		
		dateView = findViewById(R.id.fanOutInsertDate);
		dateTextView = (TextView) findViewById(R.id.fanOutInsertDateTextView);
		
		categoryView = findViewById(R.id.fanOutInsertCategoryView);
		categoryTextView = (TextView) findViewById(R.id.fanOutInsertCategoryTextView);
		
		checkView = findViewById(R.id.fanOutInsertCheckView);
		checkTextView = (TextView) findViewById(R.id.fanOutInsertCheckKind);
		bankView = findViewById(R.id.fanOutInsertBankView);
		bankTextView = (TextView) findViewById(R.id.fanOutInsertBankKind);
		creditView = findViewById(R.id.fanOutInsertCreditView);
		creditTextView = (TextView) findViewById(R.id.fanOutInsertCreditKind);
		
		nameView = findViewById(R.id.fanOutInsertNameView);
		nameTextView = (TextView) findViewById(R.id.fanOutInsertNameText);
		nameEditTextView = (EditText) findViewById(R.id.fanOutInsertNameEditText);
		nameArrow = (ImageView) findViewById(R.id.fanOutInsertNameArrow);
		
		telView = findViewById(R.id.fanOutInsertTelView);
		telTextView = (TextView) findViewById(R.id.fanOutInsertTelText);
		telEditTextView = (EditText) findViewById(R.id.fanOutInsertTelEditText);
		telArrow = (ImageView) findViewById(R.id.fanOutInsertTelArrow);
		
		outTotalMoneyView = findViewById(R.id.fanOutInsertInTotalMoneyView);
		outMyMoneyView = findViewById(R.id.fanOutInsertInMyMoneyView);
		outTotalMoneyText = (TextView) findViewById(R.id.fanOutInsertInTotalMoneyText);
		outMyMoneyText = (TextView) findViewById(R.id.fanOutInsertInMyMoneyText);
		
		moneyText = (TextView) findViewById(R.id.fanOutInsertMoneyText);
		moneyEdit = (EditText) findViewById(R.id.fanOutInsertMoneyEdit);
		EditTextInputFilter.filteringMoneyEditText(moneyEdit);
		
		memoView = findViewById(R.id.fanOutInsertMemoView);
		memoEdit = (EditText) findViewById(R.id.fanOutInsertMemoEdit);
		
		deleteButton = (Button) findViewById(R.id.fanOutDeleteButton);
		listButton = (Button) findViewById(R.id.fanOutListButton);
		insertButton = (Button) findViewById(R.id.fanOutInsertButton);
		
		if (inOutflag == UPDATE_DETAIL)
		{
			nameView.setVisibility(View.GONE);
			telView.setVisibility(View.GONE);
			outTotalMoneyView.setVisibility(View.GONE);
			outMyMoneyView.setVisibility(View.GONE);
			
			deleteButton.setVisibility(View.VISIBLE);
		}
	}
	
	private void setData()
	{
		realRadio.setChecked(true);
		checkRadio.setChecked(false);
		
		Calendar cal = Calendar.getInstance();
		year = cal.get(Calendar.YEAR);
		month = cal.get(Calendar.MONTH);
		day = cal.get(Calendar.DAY_OF_MONTH);
		dateTextView.setText(BDUtil.getDate(year, month+1, day));
		
		sql.selectMapTile(this, "SELECT kind FROM category_out_list;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int kindIdx = c.getColumnIndex("kind");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String data = c.getString(kindIdx);
					categoryList.add(data);
					
					c.moveToNext();
				}
				
				if (categoryList.size() < 1)
				{
					categoryView.setClickable(false);
					categoryTextView.setText(NONE);
				}
				else
				{
					categoryView.setClickable(true);
					categoryTextView.setText(categoryList.get(0).toString());
				}
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM check_card b, checkcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM check_card b, checkcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int nameIdx = c.getColumnIndex("name");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String data = c.getString(nameIdx);
					checkCardList.add(data);
					
					c.moveToNext();
				}
				
				if (checkCardList.size() < 1)
				{
					checkView.setClickable(false);
					checkTextView.setText(NONE);
					checkView.setTag(false);
				}
				else
				{
					checkView.setClickable(true);
					checkView.setTag(true);
					checkTextView.setText(checkCardList.get(0).toString());
				}
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name FROM bankbook b, bankbook_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int nameIdx = c.getColumnIndex("name");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String data = c.getString(nameIdx);
					bankBookList.add(data);
					
					c.moveToNext();
				}
				
				if (bankBookList.size() < 1)
				{
					bankView.setClickable(false);
					bankTextView.setText(NONE);
					bankView.setTag(false);
				}
				else
				{
					bankView.setClickable(true);
					bankView.setTag(true);
					bankTextView.setText(bankBookList.get(0).toString());
				}
			}
		});
		
		sql.selectMapTile(this, "SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count > 0 ORDER BY d.count) " +
								"UNION ALL " +
								"SELECT name FROM ( " +
								"SELECT b.name name " +
								"FROM credit_card b, creditcard_detail d " +
								"WHERE b.id = d.linkid and d.count < 1 ORDER BY d.count);", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int nameIdx = c.getColumnIndex("name");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String data = c.getString(nameIdx);
					creditCardList.add(data);
					
					c.moveToNext();
				}
				
				if (creditCardList.size() < 1)
				{
					creditView.setClickable(false);
					creditTextView.setText(NONE);
					creditView.setTag(false);
				}
				else
				{
					creditView.setClickable(true);
					creditView.setTag(true);
					creditTextView.setText(creditCardList.get(0).toString());
				}
			}
		});
		
		nameTextView.setText(NONE);
		telTextView.setText(NONE);
		
		if (inOutflag == UPDATE)
		{
			infoData = getIntent.getParcelableExtra(FanOutInfoActivity.FAN_INFO_DATA);
			
			setInfoData();
		}
		else if (inOutflag == UPDATE_DETAIL)
		{		
			infoData = getIntent.getParcelableExtra(FanInInfoActivity.FAN_INFO_DATA);
			
			setInfoData();
		}
		else if (inOutflag == CHECK)
		{
			infoData = getIntent.getParcelableExtra(FanInInfoActivity.FAN_INFO_DATA);
			
			if ( ! infoData.getCheckSign().equals("0"))
			{
				sql.selectMapTile(this, "SELECT * FROM in_out WHERE linkid = "
						+ infoData.getId() + ";", new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						int id = c.getColumnIndex("id");
						int category = c.getColumnIndex("category");
						int memo = c.getColumnIndex("memo");
						int inmoney = c.getColumnIndex("inmoney");
						int outmoney = c.getColumnIndex("outmoney");
						int date = c.getColumnIndex("date");
						int moneykind = c.getColumnIndex("moneykind");
						int postmoney = c.getColumnIndex("postmoney");
						int type = c.getColumnIndex("type");
						int linkid = c.getColumnIndex("linkid");
						int linktype = c.getColumnIndex("linktype");
						
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							checkData = new SelectData();
							checkData.setId(c.getInt(id) + "");
							checkData.setCategory(c.getString(category));
							checkData.setMemo(c.getString(memo));
							checkData.setInMoney(c.getString(inmoney));
							checkData.setOutMoney(c.getString(outmoney));
							checkData.setPostMoney(c.getString(postmoney));
							checkData.setDate(c.getInt(date) + "");
							checkData.setMoneyKind(c.getString(moneykind));
							checkData.setType(c.getInt(type) + "");
							checkData.setLinkId(c.getInt(linkid) + "");
							checkData.setLinktype(c.getInt(linktype) + "");
							
							c.moveToNext();
						}
					}
				});
			}
			nameTextView.setText(infoData.getName());
			nameView.setClickable(false);
			
			telTextView.setText(infoData.getTel());
			
			outTotalMoneyView.setVisibility(View.VISIBLE);
			outTotalMoneyText.setText(BDUtil.getWon(infoData.getMoney()) + shape);
			
			sql.selectMapTile(this, "SELECT outmoney, postmoney FROM in_out WHERE linkid = "
					+ infoData.getId() + " and category = '"
					+ BDConstents.CATEGORY_FAN_IN_CHECK + "';", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int outmoney = c.getColumnIndex("outmoney");
					int postmoney = c.getColumnIndex("postmoney");
					
					c.moveToFirst();
					
					for (int i = 0; i < c.getCount(); i++)
					{
						myOutMoney = myOutMoney.add(new BigDecimal(c.getString(outmoney)));
						myOutMoney = myOutMoney.add(new BigDecimal(c.getString(postmoney)));
						c.moveToNext();
					}
				}
			});
			outMyMoneyView.setVisibility(View.VISIBLE);
			outMyMoneyText.setText(BDUtil.getWon((
					new BigDecimal(infoData.getMoney()).subtract(myOutMoney)).toString()) + shape);
			
			moneyText.setText("이번에갚은금액");
			
			memoView.setVisibility(View.VISIBLE);
			memoEdit.setText(infoData.getName());
		}
	}
	
	/**
	 * 전 화면에서 넘어온 데이터를 셋팅한다.
	 * @param infoData
	 */
	private void setInfoData()
	{
		// 타입유무 라디오버튼 체크
		if (infoData.getType().equals(BDConstents.CHECK_TYPE))
		{
			checkRadio.setChecked(true);
			checkTextView.setText(infoData.getMoneyname());
			setCheckRadioClick();
		}
		else if (infoData.getType().equals(BDConstents.BANK_TYPE))
		{
			bankRadio.setChecked(true);
			bankTextView.setText(infoData.getMoneyname());
			setBankRadioClick();
		}
		else if (infoData.getType().equals(BDConstents.CREDIT_TYPE))
		{
			creditRadio.setChecked(true);
			creditTextView.setText(infoData.getMoneyname());
			setCreditRadioClick();
		}
		else
		{
			realRadio.setChecked(true);
		}
		
		// 날짜
		dateTextView.setText(BDUtil.getDateButton(infoData.getDate()));
		
		// 이름
		nameTextView.setText(infoData.getName());
		
		// 전화번호
		telTextView.setText(infoData.getTel());
		
		// 금액
		moneyEdit.setText(infoData.getMoney());
		
		// 내용
		if (infoData.getMemo() != null && !infoData.getMemo().equals(""))
		{
			memoView.setVisibility(View.VISIBLE);
			memoEdit.setText(infoData.getMemo());
		}
		
		if (!infoData.getCheckSign().equals("0") && inOutflag != UPDATE_DETAIL)
		{
			listButton.setVisibility(View.VISIBLE);
			
			insertButton.setText("수정");
		}
		
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE linkid = "
				+ infoData.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					checkData = new SelectData();
					checkData.setId(c.getInt(id) + "");
					checkData.setCategory(c.getString(category));
					checkData.setMemo(c.getString(memo));
					checkData.setInMoney(c.getString(inmoney));
					checkData.setOutMoney(c.getString(outmoney));
					checkData.setPostMoney(c.getString(postmoney));
					checkData.setDate(c.getInt(date) + "");
					checkData.setMoneyKind(c.getString(moneykind));
					checkData.setType(c.getInt(type) + "");
					checkData.setLinkId(c.getInt(linkid) + "");
					checkData.setLinktype(c.getInt(linktype) + "");
					
					c.moveToNext();
				}
			}
		});
	}
			
			
	private void setOnClickListener()
	{
		realRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (checkView.getVisibility() == View.VISIBLE)
				{
					checkView.setVisibility(View.GONE);
				}
				else if (bankView.getVisibility() == View.VISIBLE)
				{
					bankView.setVisibility(View.GONE);
				}
				else
				{
					creditView.setVisibility(View.GONE);
				}
			}
		});
		
		checkRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCheckRadioClick();
			}
		});
		
		bankRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setBankRadioClick();
			}
		});
		
		creditRadio.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setCreditRadioClick();
			}
		});
		
		dateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showDateDialog();
			}
		});
		
		categoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showCategoryDialog();
			}
		});
		
		checkView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showCheckDialog();
			}
		});
		
		bankView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showBankDialog();
			}
		});
		
		creditView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				showCreditDialog();
			}
		});
		
		nameView.setOnClickListener(friendClickListener);
		telView.setOnClickListener(sendClickListener);
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				BDUtil.showSelectDialog(FanOutInsertActivity.this, "알림", "정말로 삭제하시겠습니까?", 
						new DialogInterface.OnClickListener() 
				{
					@Override
					public void onClick(DialogInterface dialog, int which) 
					{
						deleteDetailData();
					}
				});
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setInsertData();
			}
		});
		
		listButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				goListData();
			}
		});
	}
	
	//TODO
	/**
	 * ProgressDialog로 빼야함
	 */
	private void deleteDetailData()
	{
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE id = "
				+ infoData.getLinkId() + " and type = '" + BDConstents.FAN_TYPE + "';", new ParseSelectData() 
		{
			@Override
			public void resultData(Cursor c) {
				SelectData data = null;
				
				int id = c.getColumnIndex("id");
				int category = c.getColumnIndex("category");
				int memo = c.getColumnIndex("memo");
				int inmoney = c.getColumnIndex("inmoney");
				int outmoney = c.getColumnIndex("outmoney");
				int date = c.getColumnIndex("date");
				int moneykind = c.getColumnIndex("moneykind");
				int postmoney = c.getColumnIndex("postmoney");
				int type = c.getColumnIndex("type");
				int linkid = c.getColumnIndex("linkid");
				int linktype = c.getColumnIndex("linktype");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					data = new SelectData();
					data.setId(c.getInt(id) + "");
					data.setCategory(c.getString(category));
					data.setMemo(c.getString(memo));
					data.setInMoney(c.getString(inmoney));
					data.setOutMoney(c.getString(outmoney));
					data.setPostMoney(c.getString(postmoney));
					data.setDate(c.getInt(date) + "");
					data.setMoneyKind(c.getString(moneykind));
					data.setType(c.getInt(type) + "");
					data.setLinkId(c.getInt(linkid) + "");
					data.setLinktype(c.getInt(linktype) + "");
					
					if (data != null)
					{
						if (data.getLinktype().equals(BDConstents.CREDIT_TYPE))
						{
							setDeleteCreditTable(data);
						}
						else if (data.getLinktype().equals(BDConstents.CHECK_TYPE))
						{
							setDeleteCheckTable(data, 1);
						}
						else if (data.getLinktype().equals(BDConstents.BANK_TYPE))
						{
							setDeleteBankBookTable(data, -1, 1, 1);
						}
						else if (data.getLinktype().equals(BDConstents.REAL_TYPE))
						{
							setDeleteRealTable(data.getId(), data.getOutMoney(), 1);
						}
					}
					
					String [] whereArgs = new String[]{infoData.getLinkId()};
					sql.delete(FanOutInsertActivity.this, "in_out", "id = ?", whereArgs);
				}
			}
		});
		
		finish();
	}
	
	/**
	 * 신용카드 테이블을 롤백시킨다.
	 * @param data 
	 */
	private void setDeleteCreditTable(final SelectData data)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int outmoneyIdx = c.getColumnIndex("outmoney");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(outmoneyIdx)));
					c.moveToNext();
				}
				
				money = money.subtract(new BigDecimal(data.getPostMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{data.getMoneyKind()}; 
				
				sql.update(FanOutInsertActivity.this, "credit_card", map, "name = ?", whereArgs);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), BDConstents.CREDIT_TYPE, 
						data.getMoneyKind(), data.getPostMoney(), 0);
			}
		});
	}
	
	/**
	 * 체크카드 테이블을 롤백시킨다.
	 * @param data
	 * @param flag 0 = 금액에서 빼기, 1 = 금액에서 더하기
	 */
	private void setDeleteCheckTable(final SelectData data, final int flag)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneyKind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int banklinkIdx = c.getColumnIndex("banklink");
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(banklinkIdx);
					c.moveToNext();
				}
				
				setDeleteBankBookTable(data, id, flag, 0);
			}
		});
	}

	/**
	 * 통장 테이블을 롤백 시킨다.
	 * @param flag 0 = 금액에서 빼기, 1 = 금액에서 더하기
	 * @param id 
	 * @param data 
	 * @param checkFlag 0 = 체크카드, 1 = 통장
	 */
	private void setDeleteBankBookTable(final SelectData data, final int id, final int flag, final int checkFlag)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		String sqlQurey = "";
		
		if (id == -1)
		{
			sqlQurey = "SELECT money FROM bankbook WHERE name = '" + BDUtil.getApostrophe(data.getMoneyKind()) + "';";
		}
		else
		{
			sqlQurey = "SELECT money FROM bankbook WHERE id = " + id + ";";
		}
		
		sql.selectMapTile(this, sqlQurey, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				int balanceFlag = 0;
				String rollMoney = "0";
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(data.getInMoney()));
					balanceFlag = 0;
					rollMoney = data.getInMoney();
				}
				else
				{
					money = money.add(new BigDecimal(data.getOutMoney()));
					balanceFlag = 1;
					rollMoney = data.getOutMoney();
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = null;
				
				if (id == -1)
				{
					whereArgs = new String[]{data.getMoneyKind()};
					sql.update(FanOutInsertActivity.this, 
							"bankbook", map, "name = ?", whereArgs);
				}
				else
				{
					whereArgs = new String[]{id + ""};
					sql.update(FanOutInsertActivity.this, 
							"bankbook", map, "id = ?", whereArgs);
				}
				
				String type = BDConstents.BANK_TYPE;
				
				if (checkFlag == 0)
				{
					type = BDConstents.CHECK_TYPE;
				}
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(data.getId(), type, 
						data.getMoneyKind(), rollMoney.toString(), balanceFlag);
			}
		});
	}
	
	/**
	 * 현금 테이블을 롤백 시킨다.
	 * @param id
	 * @param data
	 * @param flag 0 = 금액에서 빼기, 1 = 금액에서 더하기
	 */
	private void setDeleteRealTable(final String id, final String realmoney, final int flag)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT money FROM real_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(realmoney));
				}
				else
				{
					money = money.add(new BigDecimal(realmoney));
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				sql.update(FanOutInsertActivity.this, "real_money", map, null, null);
				
				BalanceQuery balanceQuery = new BalanceQuery(superContext);
				balanceQuery.setbalanceDelete(id, BDConstents.REAL_TYPE, 
						BDConstents.REAL_MONEY, realmoney.toString(), flag);
			}
		});
	}
	
	private void setCheckRadioClick()
	{
		if (creditView.getVisibility() == View.VISIBLE)
		{
			creditView.setVisibility(View.GONE);
			bankView.setVisibility(View.GONE);
		}
		else if (bankView.getVisibility() == View.VISIBLE)
		{
			bankView.setVisibility(View.GONE);
		}
		
		checkView.setVisibility(View.VISIBLE);
	}
	
	private void setBankRadioClick()
	{
		if (creditView.getVisibility() == View.VISIBLE)
		{
			creditView.setVisibility(View.GONE);
		}
		else if (checkView.getVisibility() == View.VISIBLE)
		{
			checkView.setVisibility(View.GONE);
		}
		
		bankView.setVisibility(View.VISIBLE);
	}
	
	private void setCreditRadioClick()
	{
		if (checkView.getVisibility() == View.VISIBLE)
		{
			checkView.setVisibility(View.GONE);
		}
		else if (bankView.getVisibility() == View.VISIBLE)
		{
			bankView.setVisibility(View.GONE);
		}
		
		creditView.setVisibility(View.VISIBLE);
	}
	
	private void setInsertData()
	{
		if (categoryTextView.getText().toString().equals(NONE))
		{
			BDUtil.showDialog(this, "알림", "카테고리가 없습니다. 설정 >카테고리에 가셔서 카테고리를 추가해 주세요.");
			return;
		}
		
		if (inputType == FanFriendActivity.DIRECT) 
		{
			if (nameEditTextView.getText().length() == 0)
			{
				BDUtil.showDialog(this, "알림", "이름이 없습니다. 이름을 입력해주세요.");
				return;
			}
			
			if (telEditTextView.getText().length() == 0)
			{
				BDUtil.showDialog(this, "알림", "전화번호가 없습니다. 전화번호를 입력해주세요.");
				return;
			}
		} 
		else if (inputType == FanFriendActivity.FRIEND) 
		{
			if (nameTextView.getText().toString().equals(NONE))
			{
				BDUtil.showDialog(this, "알림", "이름이 없습니다. 이름을 입력해주세요.");
				return;
			}
		} 
		else if (inputType == 0) 
		{
			if (nameTextView.getText().toString().equals(NONE))
			{
				BDUtil.showDialog(this, "알림", "이름이 없습니다. 이름을 입력해주세요.");
				return;
			}
		}
		
		if (BDUtil.getCommaDel(moneyEdit.getText().toString()).equals(""))
		{
			BDUtil.showDialog(this, "알림", "금액이 없습니다. 금액을 입력해주세요.");
			return;
		}
		
		if (checkRadio.isChecked())
		{
			if ((Boolean) checkView.getTag() == false)
			{
				BDUtil.showDialogManager(superContext, "체크카드가 하나도 없습니다.");
				return;
			}
		}
		else if (bankRadio.isChecked())
		{
			if ((Boolean) bankView.getTag() == false)
			{
				BDUtil.showDialogManager(superContext, "통장이 하나도 없습니다.");
				return;
			}
		}
		else if (creditRadio.isChecked())
		{
			if ((Boolean) creditView.getTag() == false)
			{
				BDUtil.showDialogManager(superContext, "신용카드가 하나도 업습니다.");
				return;
			}
		}
		
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}

	/**
	 * in_out 테이블에 데이터를 넣는다.
	 */
	private void setInOutTable()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		// 카테고리
		if (inOutflag == CHECK || inOutflag == UPDATE_DETAIL)
		{
			map.put("category", BDConstents.CATEGORY_FAN_IN_CHECK);
		}
		else
		{
			map.put("category", BDConstents.CATEGORY_FAN_OUT_MONEY);
		}
		
		map.put("memo", memoEdit.getText().toString());
		
		// 날짜
		String date = dateTextView.getText().toString().replaceAll(" - ", "");
		map.put("date", date);
		
		// 타입은 부채로 넣는다.
		map.put("type", BDConstents.FAN_TYPE);
		
		String type = "";
		String moneyKind = "";
		
		String inOutId = "-1";
		
		if (infoData != null)
		{
			inOutId = infoData.getLinkId();
		}
		
		if (inOutflag == UPDATE || inOutflag == UPDATE_DETAIL)
		{
			setRollBackData();
		}
		
		// 부채에 걸리는 타입을 넣는다.
		if (checkRadio.isChecked())
		{
			map.put("linktype", BDConstents.CHECK_TYPE);
			map.put("outmoney", BDUtil.getCommaDel(moneyEdit.getText().toString()));
			map.put("moneykind", checkTextView.getText().toString());
			map.put("postmoney", "0");
			
			setCheckTable(inOutId, 0, checkTextView.getText().toString(), 
					BDUtil.getCommaDel(moneyEdit.getText().toString()));
			
			type = BDConstents.CHECK_TYPE;
			moneyKind = checkTextView.getText().toString();
		}
		else if (bankRadio.isChecked())
		{
			map.put("linktype", BDConstents.BANK_TYPE);
			map.put("outmoney", BDUtil.getCommaDel(moneyEdit.getText().toString()));
			map.put("moneykind", bankTextView.getText().toString());
			map.put("postmoney", "0");
			
			setBankBookTable(inOutId, bankTextView.getText().toString(), 0, 
					BDUtil.getCommaDel(moneyEdit.getText().toString()));
			
			type = BDConstents.BANK_TYPE;
			moneyKind = bankTextView.getText().toString();
		}
		else if (creditRadio.isChecked())
		{
			map.put("linktype", BDConstents.CREDIT_TYPE);
			map.put("moneykind", creditTextView. getText().toString());
			map.put("postmoney", BDUtil.getCommaDel(moneyEdit.getText().toString()));
			map.put("outmoney", "0");
			
			setCreditTable(inOutId, 1, creditTextView.getText().toString(), 
					BDUtil.getCommaDel(moneyEdit.getText().toString()));
			
			type = BDConstents.CREDIT_TYPE;
			moneyKind = creditTextView.getText().toString();
		}
		else
		{
			map.put("linktype", BDConstents.REAL_TYPE);
			map.put("moneykind", BDConstents.REAL_MONEY);
			map.put("outmoney", BDUtil.getCommaDel(moneyEdit.getText().toString()));
			map.put("postmoney", "0");
			
			setRealTable(inOutId, 0, BDUtil.getCommaDel(moneyEdit.getText().toString()));
			
			type = BDConstents.REAL_TYPE;
			moneyKind = BDConstents.REAL_MONEY;
		}
		
		if (inOutflag == INSERT)
		{
			sql.insert(this, map, "in_out");
			
			message = BDConstents.CATEGORY_FAN_OUT_MONEY + "이 추가 되었습니다.";
			
			setFanOutTable();
			
			// 잔액을 입력한다.
			BalanceQuery balace = new BalanceQuery(superContext);
			balace.setBalance(type, moneyKind);
		}
		else if (inOutflag == UPDATE)
		{
			String [] whereArgs = new String[]{infoData.getLinkId()};
			
			sql.update(this, "in_out", map, "id = ?", whereArgs);
			
//			// 받은돈에 대한 처리 부분.
//			if (infoData.getCheckSign().equals("1"))
//			{
//				setCheckSignData();
//			}
			
//			setUpdateSignData();
			
			message = BDConstents.CATEGORY_FAN_OUT_MONEY + "이 수정 되었습니다.";
			
			setFanOutTable();
		}
		else if (inOutflag == UPDATE_DETAIL)
		{
			String [] whereArgs = new String[]{infoData.getLinkId()};
			
			sql.update(this, "in_out", map, "id = ?", whereArgs);
			
			setCheckData();
			
//			// 받은돈에 대한 처리 부분.
//			if (infoData.getCheckSign().equals("1"))
//			{
//				setCheckSignData();
//			}
//			setUpdateSignData();
//			setFanOutTable();
			message = BDConstents.CATEGORY_FAN_IN_CHECK + "이 수정 되었습니다.";
		}
		else if (inOutflag == CHECK)
		{
			map.put("linkid", infoData.getId());
			sql.insert(this, map, "in_out");
			
			message = BDConstents.CATEGORY_FAN_IN_CHECK + "이 확인 되었습니다.";
			
			setCheckData();
			
			// 잔액을 입력한다.
			BalanceQuery balace = new BalanceQuery(superContext);
			balace.setBalance(type, moneyKind);
		}
	}
	
	/**
	 * fan_in 테이블 셋팅
	 */
	BigDecimal totalMoney = BigDecimal.ZERO;
	private void setCheckData()
	{
		if (!infoData.getCheckSign().equals("0"))
		{
			sql.selectMapTile(this, "SELECT money FROM fan_in WHERE id ="
					+ checkData.getId() + ";", new ParseSelectData() 
			{
				@Override
				public void resultData(Cursor c) {
					
					int money = c.getColumnIndex("money");
					
					c.moveToFirst();
					
					for (int i=0; i<c.getCount(); i++)
					{
						totalMoney = new BigDecimal(c.getString(money));
					}
				}
			});
		}
		
		sql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int maxIdIdx = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					maxId = c.getInt(maxIdIdx);
					c.moveToNext();
				}
			}
		});
		
		sql.selectMapTile(this, "SELECT outmoney, postmoney FROM in_out WHERE linkid = "
				+ infoData.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal money = BigDecimal.ZERO;
				
				int omoneyIdx = c.getColumnIndex("outmoney");
				int pmoneyIdx = c.getColumnIndex("postmoney");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(omoneyIdx)));
					money = money.add(new BigDecimal(c.getString(pmoneyIdx)));
					c.moveToNext();
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("checkid", maxId + "");
				
				BigDecimal compareMoney = BigDecimal.ZERO;
				if (totalMoney != null)
				{	
					compareMoney = totalMoney;
				}
				else
				{
					infoData.getMoney();
				}
				if (money.compareTo(compareMoney) > -1)
				{
					map.put("checksign", "1");
				}
				else if (money.compareTo(BigDecimal.ZERO) == 0)
				{
					map.put("checksign", "0");
				}
				else 
				{
					map.put("checksign", "2");
				}

				String [] whereArgs = new String[]{infoData.getId()};
				
				sql.update(FanOutInsertActivity.this, "fan_in", map, "id = ?", whereArgs);
			}
		});
	}
	
	/**
	 * 수정에 위하여 데이터를 롤백 시킨다.
	 */
	private void setRollBackData()
	{
		// 부채에 걸리는 타입을 넣는다.
		if (infoData.getType().equals(BDConstents.CHECK_TYPE))
		{
			setCheckTable(infoData.getLinkId(), 1, infoData.getMoneyname(), infoData.getMoney());
		}
		else if (infoData.getType().equals(BDConstents.BANK_TYPE))
		{
			setBankBookTable(infoData.getLinkId(), infoData.getMoneyname(), 1, infoData.getMoney());
		}
		else if (infoData.getType().equals(BDConstents.CREDIT_TYPE))
		{
			setCreditTable(infoData.getLinkId(), 0, infoData.getMoneyname(), infoData.getMoney());
		}
		else
		{
			setRealTable(infoData.getId(), 1, infoData.getMoney());
		}
	}

	/**
	 * 받을돈 테이블 셋팅
	 */
	private void setFanOutTable()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		if (inputType == FanFriendActivity.DIRECT) 
		{
			// 이름
			map.put("name", nameEditTextView.getText().toString());
			
			// 전화번호
			map.put("tel", telEditTextView.getText().toString());
		} 
		else if (inputType == FanFriendActivity.FRIEND) {
			// 이름
			map.put("name", nameTextView.getText().toString());
			
			// 전화번호
			map.put("tel", telTextView.getText().toString());
		}
		
		// 날짜
		String date = dateTextView.getText().toString().replaceAll(" - ", "");
		map.put("date", date);
		
		// 금액
		map.put("money", BDUtil.getCommaDel(moneyEdit.getText().toString()));
		
		map.put("memo", memoEdit.getText().toString());
		
		// 타입
		if (checkRadio.isChecked())
		{
			map.put("type", BDConstents.CHECK_TYPE);
			map.put("moneyname", checkTextView.getText().toString());
		}
		else if (bankRadio.isChecked())
		{
			map.put("type", BDConstents.BANK_TYPE);
			map.put("moneyname", bankTextView.getText().toString());
		}
		else if (creditRadio.isChecked())
		{
			map.put("type", BDConstents.CREDIT_TYPE);
			map.put("moneyname", creditTextView.getText().toString());
		}
		else
		{
			map.put("type", BDConstents.REAL_TYPE);
			map.put("moneyname", "");
		}
		
		if (inOutflag == INSERT)
		{
			sql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int maxIdIdx = c.getColumnIndex("maxid");
					
					c.moveToFirst();
					
					for (int i = 0; i < c.getCount(); i++)
					{
						maxId = c.getInt(maxIdIdx);
						c.moveToNext();
					}
				}
			});
			
			map.put("linkid", maxId + "");
			
			sql.insert(this, map, "fan_out");
		}
		else if (inOutflag == UPDATE)
		{
			String [] whereArgs = new String[]{infoData.getId()};
			
			sql.update(this, "fan_out", map, "id = ?", whereArgs);

			
			sql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int maxIdIdx = c.getColumnIndex("maxid");
					
					c.moveToFirst();
					
					for (int i = 0; i < c.getCount(); i++)
					{
						maxId = c.getInt(maxIdIdx);
						c.moveToNext();
					}
				}
			});
			
			sql.selectMapTile(this, "SELECT inmoney FROM in_out WHERE linkid = "
					+ infoData.getId() + ";", new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					BigDecimal money = BigDecimal.ZERO;
					
					int moneyIdx = c.getColumnIndex("inmoney");
					
					c.moveToFirst();
					
					for (int i = 0; i < c.getCount(); i++)
					{
						money = money.add(new BigDecimal(c.getString(moneyIdx)));
						c.moveToNext();
					}
					
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("checkid", maxId + "");
					
					if (money.compareTo(new BigDecimal(BDUtil.getCommaDel(moneyEdit.getText().toString()))) > -1)
					{
						map.put("checksign", "1");
					}
					else if (money.compareTo(BigDecimal.ZERO) == 0)
					{
						map.put("checksign", "0");
					}
					else 
					{
						map.put("checksign", "2");
					}
					
					String [] whereArgs = new String[]{infoData.getId()};
					
					sql.update(FanOutInsertActivity.this, "fan_out", map, "id = ?", whereArgs);
				}
			});
		}
	}

	/**
	 * 체크카드 테이블을 셋팅한다.
	 * 0 = 금액 빼기, 1 = 금액 더하기
	 */
	private void setCheckTable(final String inOutId, final int flag, final String cardName, final String tempMoney)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT banklink FROM check_card WHERE name = '"
				+ BDUtil.getApostrophe(cardName) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int banklinkIdx = c.getColumnIndex("banklink");
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(banklinkIdx);
					c.moveToNext();
				}
				
				setBankBookTable(inOutId, id, flag, tempMoney, cardName);
			}
		});
	}
	
	/**
	 * 통장 테이블을 셋팅한다.
	 * @param inOutId
	 * @param id
	 * @param tempMoney
	 * @param flag 0 = 금액 빼기, 1 = 금액 더하기
	 * @param cardName
	 */
	private void setBankBookTable(final String inOutId, final int id, 
			final int flag, final String tempMoney, final String cardName)
	{
		sql.selectMapTile(this, "SELECT money FROM bankbook WHERE id = "
				+ id + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(tempMoney));
				}
				else if (flag == 1)
				{
					money = money.add(new BigDecimal(tempMoney));
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""};
				
				sql.update(FanOutInsertActivity.this, "bankbook", map, "id = ?", whereArgs);
				
				if (inOutflag == UPDATE)
				{
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setBalanceUpdateRollBank(inOutId, BDConstents.CHECK_TYPE, 
							cardName, tempMoney.toString(), flag);
				}
			}
		});
	}
	
	/**
	 * 통장 테이블을 셋팅한다.
	 * @param id
	 * @param name
	 * @param tempMoney
	 * @param flag 0 = 금액 빼기, 1 = 금액 더하기
	 */
	private void setBankBookTable(final String id, final String name, final int flag, final String tempMoney)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(name) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(tempMoney));
				}
				else if (flag == 1)
				{
					money = money.add(new BigDecimal(tempMoney));
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{name + ""};
				
				sql.update(FanOutInsertActivity.this, "bankbook", map, "name = ?", whereArgs);
				
				if (inOutflag == UPDATE)
				{
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setBalanceUpdateRollBank(id, BDConstents.BANK_TYPE, 
							name, tempMoney.toString(), flag);
				}
			}
		});
	}
	
	/**
	 * 신용카드 테이블을 셋팅한다.
	 * 0 = 금액 빼기, 1 = 금액 더하기
	 */
	private void setCreditTable(final String id, final int flag, final String cardName, final String tempMoney)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(cardName) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("outmoney");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(tempMoney));
				}
				else if (flag == 1)
				{
					money = money.add(new BigDecimal(tempMoney));
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{cardName};
				
				sql.update(FanOutInsertActivity.this, "credit_card", map, "name = ?", whereArgs);
				
				if (inOutflag == UPDATE)
				{
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setBalanceUpdateRollBank(id, BDConstents.CREDIT_TYPE, 
							cardName, tempMoney.toString(), flag);
				}
			}
		});
	}
	
	/**
	 * 현금 테이블을 셋팅한다.
	 * 0 = 금액 빼기, 1 = 금액 더하기
	 */
	private void setRealTable(final String id, final int flag, final String tempMoney)
	{
		// 부채 자산 미포함일 경우에 바로 리턴한다.
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int checkManagerFlag = pref.getInt(BDConstents.FAN_MANAGER_SETTING_OK_NO, 0);
		
		if (checkManagerFlag == 1)
		{
			return;
		}
		
		sql.selectMapTile(this, "SELECT money FROM real_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int moneyIdx = c.getColumnIndex("money");
				BigDecimal money = BigDecimal.ZERO;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				if (flag == 0)
				{
					money = money.subtract(new BigDecimal(tempMoney));
				}
				else if (flag == 1)
				{
					money = money.add(new BigDecimal(tempMoney));
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				sql.update(FanOutInsertActivity.this, "real_money", map, null, null);
				
				if (inOutflag == UPDATE)
				{
					BalanceQuery balanceQuery = new BalanceQuery(superContext);
					balanceQuery.setBalanceUpdateRollBank(id, BDConstents.REAL_TYPE, 
							BDConstents.REAL_MONEY, tempMoney.toString(), flag);
				}
			}
		});
	}
	
	private OnClickListener friendClickListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			Intent intent = new Intent(FanOutInsertActivity.this, FanFriendActivity.class);
			intent.putExtra(FanFriendActivity.FAN_NAME, nameTextView.getText().toString());
			intent.putExtra(FanFriendActivity.FAN_TEL, telTextView.getText().toString());
			startActivityForResult(intent, REQUEST_TEL_NAME);
		}
	};
	
	private OnClickListener sendClickListener = new OnClickListener()
	{
		@Override
		public void onClick(View v)
		{
			// 전화번호가 없을 경우 다이얼로그를 뛰우지 않는다.
			if (telTextView.getText().toString().equals(NONE))
			{
				return;
			}
			
			AlertDialog.Builder dialog = new AlertDialog.Builder(FanOutInsertActivity.this);
			
			View view = getLayoutInflater().inflate(R.layout.view_send_dialog, null);
			
			View telView = view.findViewById(R.id.sendDialogTelView);
			View smsView = view.findViewById(R.id.sendDialogSmsView);
			
			dialog.setView(view);
			
			telView.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					// Intent.ACTION_CALL 전화 바로 걸기.
					// Intent.ACTION_DIAL 전화 걸기 화면으로 이동.
					
					Intent intent = new Intent(
							Intent.ACTION_DIAL, Uri.parse("tel:" + telTextView.getText().toString()));
					startActivity(intent);
				}
			});
			
			smsView.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v)
				{
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.putExtra("address", telTextView.getText().toString()); // 받는사람 번호
					intent.setType("vnd.android-dir/mms-sms");
					startActivity(intent);
				}
			});
			
			dialog.show();
		}
	};

	/**
	 * 날짜 다이얼로그를 뛰운다.
	 */
	private void showDateDialog()
	{
//		DatePickerDialog dialog = new DatePickerDialog(this, new OnDateSetListener()
//		{
//			@Override
//			public void onDateSet(DatePicker view, int toYear, int monthOfYear,
//					int dayOfMonth)
//			{
//				dateTextView.setText(BDUtil.getDate(toYear, (monthOfYear+1), dayOfMonth));
//				
//				year = toYear;
//				month = monthOfYear;
//				day = dayOfMonth;
//			}
//		}, year, month, day);
//		
//		dialog.show();
		
		CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
			@Override
			public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
				
				dateTextView.setText(BDUtil.getDate(year, (monthOfYear+1), dayOfMonth));
				
				FanOutInsertActivity.this.year = year;
				month = monthOfYear;
				day = dayOfMonth;
				
			}
		}, year, month, day);
		
		cpd.show();
		
	}
	
	/**
	 * 카테고리 다이얼로그를 뛰운다.
	 */
	private void showCategoryDialog()
	{
		Intent intent = new Intent(this, RadioDialogActivity.class);
		intent.putExtra(RadioDialogActivity.RADIODATA, categoryList);
		intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryTextView.getText().toString());
		startActivityForResult(intent, REQUEST_CATEGORY);
	}
	
	/**
	 * 체크카드 다이얼로그를 뛰운다.
	 */
	private void showCheckDialog()
	{
		Intent intent = new Intent(this, RadioDialogActivity.class);
		intent.putExtra(RadioDialogActivity.RADIODATA, checkCardList);
		intent.putExtra(RadioDialogActivity.RADIOSELECT, checkTextView.getText().toString());
		startActivityForResult(intent, REQUEST_CHECK);
	}
	
	/**
	 * 통장 다이얼로그를 뛰운다.
	 */
	private void showBankDialog()
	{
		Intent intent = new Intent(this, RadioDialogActivity.class);
		intent.putExtra(RadioDialogActivity.RADIODATA, bankBookList);
		intent.putExtra(RadioDialogActivity.RADIOSELECT, bankTextView.getText().toString());
		startActivityForResult(intent, REQUEST_BANK);
	}
	
	/**
	 * 신용카드 다이얼로그를 뛰운다.
	 */
	private void showCreditDialog()
	{
		Intent intent = new Intent(this, RadioDialogActivity.class);
		intent.putExtra(RadioDialogActivity.RADIODATA, creditCardList);
		intent.putExtra(RadioDialogActivity.RADIOSELECT, creditTextView.getText().toString());
		startActivityForResult(intent, REQUEST_CREDIT);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_CHECK)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				checkTextView.setText(selectData);
			}
		}
		else if (requestCode == REQUEST_BANK)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				bankTextView.setText(selectData);
			}
		}
		else if (requestCode == REQUEST_TEL_NAME)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				inputType = data.getIntExtra(FanFriendActivity.INPUT_TYPE, FanFriendActivity.DIRECT);
				switch (inputType) {
					case FanFriendActivity.DIRECT:
						if (nameTextView.getVisibility() == View.VISIBLE) {
							nameTextView.setVisibility(View.GONE);
							nameArrow.setVisibility(View.GONE);
							nameEditTextView.setVisibility(View.VISIBLE);
						}
						if (telTextView.getVisibility() == View.VISIBLE) {
							telTextView.setVisibility(View.GONE);
							telArrow.setVisibility(View.GONE);
							telEditTextView.setVisibility(View.VISIBLE);
						}
						nameEditTextView.setText(data.getStringExtra(FanFriendActivity.FAN_NAME));
						telEditTextView.setText(data.getStringExtra(FanFriendActivity.FAN_TEL));
						
						break;
					case FanFriendActivity.FRIEND:
						if (nameEditTextView.getVisibility() == View.VISIBLE) {
							nameEditTextView.setVisibility(View.GONE);
							nameArrow.setVisibility(View.VISIBLE);
							nameTextView.setVisibility(View.VISIBLE);
						}
						if (telEditTextView.getVisibility() == View.VISIBLE) {
							telEditTextView.setVisibility(View.GONE);
							telArrow.setVisibility(View.VISIBLE);
							telTextView.setVisibility(View.VISIBLE);
						}
						nameTextView.setText(data.getStringExtra(FanFriendActivity.FAN_NAME));
						telTextView.setText(data.getStringExtra(FanFriendActivity.FAN_TEL));
						
						break;
					default:
						break;
				}
			}
		}
		else if (requestCode == REQUEST_CATEGORY)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				categoryTextView.setText(data.getStringExtra(RadioDialogActivity.RADIOSTRING));
			}
		}
		else if (requestCode == REQUEST_CREDIT)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				creditTextView.setText(selectData);
			}
		}
	}
	
	ArrayList<FanData> list = new ArrayList<FanData>();
	private void goListData()
	{
		list.clear();
		
		sql.selectMapTile(this, "SELECT * FROM in_out WHERE linkid = "
				+ infoData.getId() + ";", new ParseSelectData() {
			@Override
			public void resultData(Cursor c)
			{
				int id = c.getColumnIndex("id");
				int date = c.getColumnIndex("date");
				int inmoney = c.getColumnIndex("inmoney");
				int moneykind = c.getColumnIndex("moneykind");
				int memo = c.getColumnIndex("memo");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					FanData data = new FanData();
					data.setId(infoData.getId());
					data.setCheckSign(infoData.getCheckSign());
					data.setLinkId(c.getInt(id)+"");
					data.setDate(c.getString(date));
					if (c.getString(moneykind) != null)
					{
						data.setType(BDConstents.BANK_TYPE);
						data.setMoneyname(c.getString(moneykind));
					}
					else
					{
						data.setType(BDConstents.REAL_TYPE);
					}
					data.setMoney(c.getString(inmoney));
					data.setMemo(c.getString(memo));
					//data.setCheckSign("-1");
					
					list.add(data);
					
					c.moveToNext();
				}
			}
		});
		
		Intent intent = new Intent(FanOutInsertActivity.this, FanUpdateListActivity.class);
		intent.putParcelableArrayListExtra(FanUpdateListActivity.FAN_UPDATE_DATA, list);
		intent.putExtra(FanUpdateListActivity.FAN_UPDATE_FLAG, FanUpdateListActivity.IN);
		startActivity(intent);
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(FanOutInsertActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loding...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 1)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setInOutTable();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
			} else 
				return arg0[0];
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1)
			{
				BDUtil.showDialogFinish(FanOutInsertActivity.this, "확인", message);
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
